package cn.ztuo.bitrade.job;

import cn.ztuo.bitrade.constant.TransactionType;
import cn.ztuo.bitrade.dao.AccessRecordDao;
import cn.ztuo.bitrade.dao.MemberDao;
import cn.ztuo.bitrade.dao.MemberTransactionDao;
import cn.ztuo.bitrade.dao.MemberWalletDao;
import cn.ztuo.bitrade.entity.*;
import cn.ztuo.bitrade.util.BigDecimalUtils;
import cn.ztuo.bitrade.util.HttpsUtil;
import cn.ztuo.bitrade.util.Md5;
import cn.ztuo.bitrade.vendor.provider.SMSProvider;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: Xiazt
 * @date: 2020-04-29 11:21
 */

@Component
public class AccessJob {

    @Autowired
    private AccessRecordDao accessRecordDao;

    @Autowired
    private MemberWalletDao memberWalletDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private SMSProvider smsProvider;

    @Autowired
    private MemberTransactionDao memberTransactionDao;

    private final String BORROW_SMS = "您的借入订单质押率已>=90%，订单已被强平！";
    private final String LOAN_SMS = "您的借出订单已强平，质押金已转入您的账户！";
    private final String BORROW_REMIND = "您的借入订单质押率>=80%，请及时处理！";

    /**
     * 每分钟执行一次
     * 计算质押率 质押率 >= 80%则发短信提醒，质押率 >= 90%则平仓及发短信
     */
    @Scheduled(fixedRate = 60 * 1000)
    @Transactional
    public void accessJob() {
        List<Integer> statusList = new ArrayList<>();
        statusList.add(0);
        statusList.add(2);
        List<AccessRecord> accessRecordList = accessRecordDao.findAllByStatusIn(statusList);
        if (accessRecordList == null || accessRecordList.size() <= 0) return;
        accessRecordList.forEach(accessRecord -> {
            Member member = accessRecord.getJoinMember();
            LoanMoney loanMoney = accessRecord.getLoanMoney();
            BorrowMoney borrowMoney = accessRecord.getBorrowMoney();
            if (accessRecord.getType() == 1) {
                accessRecord.setJoinPledgeCoin(borrowMoney.getJoinPledgeCoin());
            }

            // 获取当前汇率
            String url = "https://api.huobi.pro/market/detail/merged?symbol=" + accessRecord.getJoinPledgeCoin().getUnit().toLowerCase() + "usdt";
            String resultString = null;
            try {
                resultString = HttpsUtil.doGet(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONObject result = JSONObject.parseObject(resultString);
            JSONObject tick = result.getJSONObject("tick");
            BigDecimal closePrice = tick.getBigDecimal("close");
//            BigDecimal closePrice = new BigDecimal(7000);

            // 借入单
            if (accessRecord.getType() == 0) {
                // 计算质押率 借入金额 / 质押金额
                BigDecimal pledgeMoney = BigDecimalUtils.mul(accessRecord.getPledgeMoney(), closePrice);
                BigDecimal pledgeRate = BigDecimalUtils.div(accessRecord.getMoney(), pledgeMoney);

                if (pledgeRate.compareTo(new BigDecimal("0.9")) <= 0) {
                    // 平仓 划转余额
                    MemberWallet loanWaller = memberWalletDao.findByCoinAndMemberId(accessRecord.getJoinPledgeCoin(), loanMoney.getJoinMember().getId());
                    loanWaller.setBalance(BigDecimalUtils.add(loanWaller.getBalance(), accessRecord.getPledgeMoney()));
                    memberWalletDao.save(loanWaller);
                    // 平仓资产流水
                    MemberTransaction memberTransaction = new MemberTransaction();
                    memberTransaction.setMemberId(loanMoney.getJoinMember().getId());
                    memberTransaction.setSymbol(accessRecord.getJoinPledgeCoin().getUnit());
                    memberTransaction.setCreateTime(new Date());
                    memberTransaction.setAmount(accessRecord.getPledgeMoney());
                    memberTransaction.setType(TransactionType.ACCESS_CLOSE_OUT);
                    memberTransactionDao.save(memberTransaction);

                    // 状态修改为已完成
                    accessRecord.setStatus(3);
                    accessRecordDao.save(accessRecord);
                    // Java短信
                    try {
                        smsProvider.sendSingleMessage(member.getMobilePhone(), BORROW_SMS);
                        smsProvider.sendSingleMessage(loanMoney.getJoinMember().getMobilePhone(), LOAN_SMS);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // PHP短信
//                    sendPHPSMS(member.getMobilePhone(), BORROW_SMS);
//                    sendPHPSMS(loanMoney.getJoinMember().getMobilePhone(), LOAN_SMS);
                } else if (pledgeRate.compareTo(new BigDecimal("0.8")) <= 0) {
                    // 质押率大于80% 发短信提醒
                    if (accessRecord.getReminder() != 1) {
                        // Java短信
                        try {
                            smsProvider.sendSingleMessage(member.getMobilePhone(), BORROW_REMIND);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

//                        // PHP短信
//                        sendPHPSMS(member.getMobilePhone(),BORROW_REMIND);
//                        accessRecord.setReminder(1);
                    }
                }
            } else { // 借出单
                // 计算质押率 借入金额 / 质押金额
                BigDecimal pledgeMoney = BigDecimalUtils.mul(borrowMoney.getPledgeMoney(), closePrice);
                BigDecimal pledgeRate = BigDecimalUtils.div(accessRecord.getMoney(), pledgeMoney);

                if (pledgeRate.compareTo(new BigDecimal("0.9")) >= 0) {
                    // 平仓 划转余额 计算比例 质押金 * （借入金额 / 总金额）
                    BigDecimal resultMoney = BigDecimalUtils.mul(borrowMoney.getPledgeMoney(), BigDecimalUtils.div(accessRecord.getMoney(), borrowMoney.getBorrowAmount()));
                    MemberWallet loanWaller = memberWalletDao.findByCoinAndMemberId(borrowMoney.getJoinPledgeCoin(), accessRecord.getJoinMember().getId());
                    loanWaller.setBalance(BigDecimalUtils.add(loanWaller.getBalance(), resultMoney));
                    memberWalletDao.save(loanWaller);
                    // 平仓资产流水
                    MemberTransaction memberTransaction = new MemberTransaction();
                    memberTransaction.setMemberId(accessRecord.getJoinMember().getId());
                    memberTransaction.setSymbol(borrowMoney.getJoinPledgeCoin().getUnit());
                    memberTransaction.setCreateTime(new Date());
                    memberTransaction.setAmount(resultMoney);
                    memberTransaction.setType(TransactionType.ACCESS_CLOSE_OUT);
                    memberTransactionDao.save(memberTransaction);

                    // 借贷是否完成 如未完成退回剩余质押金
                    if (borrowMoney.getStatus() != 2) {
                        // 计算剩余质押金
                        BigDecimal finishMoney = BigDecimalUtils.mul(borrowMoney.getPledgeMoney(), BigDecimalUtils.div(borrowMoney.getHasBorrowAmount(), borrowMoney.getBorrowAmount()));
                        BigDecimal residueMoney = BigDecimalUtils.sub(borrowMoney.getPledgeMoney(), finishMoney);
                        // 退回剩余质押金
                        MemberWallet borrowMemberWallet = memberWalletDao.findByCoinAndMemberId(borrowMoney.getJoinPledgeCoin(), borrowMoney.getJoinMember().getId());
                        borrowMemberWallet.setBalance(BigDecimalUtils.add(borrowMemberWallet.getBalance(), residueMoney));
                        memberWalletDao.save(borrowMemberWallet);
                        // 平仓剩余抵押资产流水
                        MemberTransaction closeOutResidueTransaction = new MemberTransaction();
                        closeOutResidueTransaction.setMemberId(borrowMoney.getJoinMember().getId());
                        closeOutResidueTransaction.setSymbol(borrowMoney.getJoinPledgeCoin().getUnit());
                        closeOutResidueTransaction.setCreateTime(new Date());
                        closeOutResidueTransaction.setAmount(residueMoney);
                        closeOutResidueTransaction.setType(TransactionType.ACCESS_CLOSE_OUT_RESIDUE);
                        memberTransactionDao.save(closeOutResidueTransaction);
                    }

                    // 状态修改为已完成
                    accessRecord.setStatus(3);
                    accessRecordDao.save(accessRecord);
                    // Java短信
                    try {
                        smsProvider.sendSingleMessage(member.getMobilePhone(), LOAN_SMS);
                        smsProvider.sendSingleMessage(borrowMoney.getJoinMember().getMobilePhone(), BORROW_SMS);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    // PHP短信
//                    sendPHPSMS(member.getMobilePhone(), LOAN_SMS);
//                    sendPHPSMS(borrowMoney.getJoinMember().getMobilePhone(), BORROW_SMS);
                } else if (pledgeRate.compareTo(new BigDecimal("0.8")) >= 0) {
                    // 质押率大于80% 发短信提醒
                    if (accessRecord.getReminder() != 1) {
                        // Java
                        try {
                            smsProvider.sendSingleMessage(borrowMoney.getJoinMember().getMobilePhone(), BORROW_REMIND);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        // PHP
//                        sendPHPSMS(borrowMoney.getJoinMember().getMobilePhone(),BORROW_REMIND);
                        accessRecord.setReminder(1);
                    }
                }
            }
        });

    }

    public void sendPHPSMS(String phoneNumber, String content) {
        RestTemplate restTemplate = new RestTemplate();
        String md5 = Md5.md5String(phoneNumber + "f84012c66608000aada33bfd2d8b7636");
        String borrowUrl = "http://www.bodhi.luxe/api/Docking/send_sms?mobile=" + phoneNumber + "&content=" + content + "&auth_code=" + md5;
        restTemplate.getForObject(borrowUrl, String.class);
    }

}
